package com.vince.vinceSo.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vince.vinceSo.model.entity.Post;
import com.vince.vinceSo.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取初始帖子列表
 *
 */
// todo 取消注释开启任务
//@Component
@Slf4j
public class FetchinitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Override
    public void run(String... args) {
        //1. 获取数据
        String json = "{\"reviewStatus\":1,\"needNotInterests\":true,\"hiddenContent\":true,\"needCursor\":true,\"needFilterVipContent\":true,\"needOnlyRecommend\":true,\"cursorList\":[{\"field\":\"recommendTime\",\"value\":1736605551000,\"asc\":false},{\"field\":\"id\",\"value\":\"1878085919437697025\",\"asc\":false}],\"queryType\":\"recommend\"}";
        String url = "https://api.codefather.cn/api/recommend/list/page/vo";
        String result = HttpRequest
                .post(url)
                .body(json)
                .execute()
                .body();
        //2. json转对象
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tempRecord = (JSONObject) record;
            Post post = new Post();
            post.setTitle(tempRecord.getStr("title"));
            post.setContent(tempRecord.getStr("content"));

            JSONArray tags = (JSONArray) tempRecord.get("tags");
            if (tags.size() != 0) {
                List<String> tagsList = tags.toList(String.class);
                post.setTags(JSONUtil.toJsonStr(tagsList));
            }
            post.setUserId(1L);
            postList.add(post);
        }
        //3. 数据入库
        boolean b = postService.saveBatch(postList);
        if (b) {
            log.info("获取初始化帖子列表成功。条数 = {}",postList.size());
        }else {
            log.error("获取初始化帖子列表失败");
        }
    }
}
